package com.bfxy.kafka.api.consumer.multithread1;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;

import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;

public class KafkaConsumerMt1 implements Runnable {

    private final KafkaConsumer<String, String> consumer;

    private volatile boolean isRunning = true;

    private static final AtomicInteger counter = new AtomicInteger(0);
    private final String consumerName;

    public KafkaConsumerMt1(Properties properties, String topic) {
        this.consumer = new KafkaConsumer<>(properties);
        this.consumer.subscribe(Collections.singletonList(topic));
        this.consumerName = "KafkaConsumerMt1-" + counter.getAndIncrement();
        System.out.println(this.consumerName + " started ");
    }

    @Override
    public void run() {
        try {
            while (isRunning) {
                // ConsumerRecords包含订阅topic下的所有partition的消息内容
                ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofMillis(1000));
                for (TopicPartition partition : consumerRecords.partitions()) {
                    // 根据具体的TopicPartition获取对应partition下的消息集合
                    List<ConsumerRecord<String, String>> records = consumerRecords.records(partition);
                    for (ConsumerRecord<String, String> record : records) {
                        String message = record.value();
                        long offset = record.offset();
                        System.out.println("当前消费者：" + consumerName + "，当前分区：" + partition.partition() + "，消息内容：" + message + "，消息的偏移量：" + offset + "，当前线程：" + Thread.currentThread().getName());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (consumer != null) {
                consumer.close();
            }
        }
    }

    public boolean isRunning() {
        return isRunning;
    }

    public void setRunning(boolean running) {
        isRunning = running;
    }
}
